package com.example.config;

import org.apache.logging.log4j.ThreadContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Description:
 *
 * @Author maduar maduar@163.com
 * @Date 2021-08-02 23:27
 */
@Component
@Aspect
public class LogInspect implements HandlerInterceptor {

    @Pointcut("@annotation(com.example.config.SplunkLog)")
    public void point(){
    }

    @Around("point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        //防止不是http请求的方法，例如：scheduled
        if(Objects.isNull(ra)){
            return joinPoint.proceed();
        }
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        // 可以在这里做很多事情
        ThreadContext.put("aaa", "aaa");

        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            ThreadContext.clearMap();
            return null;
        }
    }

    @After("point()")
    public void after() {
        ThreadContext.clearMap();
    }

}
